using Aop.Api;
using Aop.Api.Domain;
using Aop.Api.Request;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Mvc;
using MovieAPI.Models;
using System.Data.Entity;

namespace MovieAPI.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*"), RequireHttpsAttribute]
    public class OrderController : ApiController
    {
        private filmEntities db = new filmEntities();

        //沙箱环境，请求支付链接的地址           
        const string URL = "https://openapi.alipaydev.com/gateway.do";
        //支付宝正式环境 
        //https://openapi.alipaydev.com/gateway.do   
        //APPID即创建应用后生成,沙箱环境中的AppId
        const string APPID = "2016102800773153";
        //这里是我们之前用秘钥工具生成的商户私钥
        const string APP_PRIVATE_KEY = "MIIEpAIBAAKCAQEAns3Ntk6itqaKGRrgwxM9Iu++PIYYWvHsC3l+HEs16NaRBgKkn61NYui7kMeFMn4Y+GxNLo0NJ07Bi1oJM3yrjxK/pwGXDImUwcKi8kFBDostFyU5x9BT4/qppSkMHim1YBVniDs2ejp4EUNhhrYYUA2GbXvk/wUEXzaYryc1HtfG6kl2jiDRZn1wjQLbxd4Vsf3lFc7L23nI2E266Kq2yYwydLbe1ozKfP3ZWSE0Nc7EJbt1Az7muHwG4U4WJlmv8phityw5vmlBPT3zYGsxoE24C1qXv3X7iK0tkNrtJ94RWI2kTiQ1Wbo7n+d/UHSlM1AyYfnfFffJdrpqmocvZwIDAQABAoIBAGCFwtVecnQGQcYEmjy3wt8rTTvIXaFZjhljXQ2hgUDmufsnPBx536GQyAC15PXNwyur2DXFMguESQuETDdpPXWW9bpysvbB4RLsVNJea0aFvYBl9frHW1Ykk1x52I202DNwjx80rmYYh8YmaG7S23A86Eo/le6ThBbDPoanlBgMJeuOOi81rxNlKj/JygeHNO6XkxBgZNmI2pI3+bsJ8IS4VtJJCyxd7LB06hK5ywKNzc8yErIY8YrL+YgjvwATzHtAawAzj7OIpdanuYsn/MaFPWjx2lfp1ULpSgZv1d1ZofVt6EVpWd80ZIEgyJJf/StjQt97rtubNyZZ1ahhmaECgYEA0TGzdbFaHhYBr9tLommvxCiGqrJS0TNqhubdASICP4xDg+VEz5Bmc6wEDPuv2qxMhKsJvl8/wtNpHFKMHaHBSUcY7tzHJ5HII5EkpLxqSfIRkZFdfDY96HSeyDOkFPE4ew199YWK9y18c+tekzqZZpa5MjsnFL4Mtnt4uqQxyt8CgYEAwlXVMSs721h6BRFeut/uvjAEHaLQ8dbsvuV7s+iKphx9Ubq/02t4A+wzoorknsafBjYSKmWOs5WAgHCR4QyDpvSgqfl7wfz3iG/EoMslHQF/se8gPYWRS3yj7PtCg3Nu+kkOl5ZygetRQTlJ6sRS9qmlZQhiE8d1hoXfoRBXNHkCgYEAh3pjmcYI8dEYuJYSDpXZgfUo+aVRIzDkPYeH+3LV9+fT1biGbtI6t5DgcrQROFI7n/PQ9JxlA7y8pt4C5jHapqVHzXHn/IVaE0atb46iW09M93QoEghi4YedSVTAX9u002Ryfa5FyDyKC9yTvE/IBvt35sMOVU2bmBawolcx9AsCgYEAn1nYff/wjhUHwR4UKnIzBzrCNTbr1FKjQIlWHRjikAEudZUHdKpb+AN396Gig9tkTKiLzr4F/JXrj+Y+iGZFkeJn19jeNRxkMTlM53iMTzOKbPIi4q+ii16B4HHLgZRm/M5pK73O2V+G+k+qn9oqGV7UY3szSPq2EP+3dw+6IikCgYBs/f7KL4xH83abRHh9HASuW6+bDfTSIjCobcbildKketWEU8JdlytYLkb8vuaGlvQzv+EwxaffqY2FIMm1mH1mntr5ht6l70eD+q+NwxCbUE3pJePAY3yP5kLawwMZIq062LNHhc0p381cPiey477Pf/ZQj/xPUVEGu1lqAqSRkQ==";
        //参数返回格式，只支持json
        const string FORMAT = "json";
        //支持GBK和UTF-8
        const string CHARSET = "UTF-8";
        //支付宝公钥
        const string ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhxGCRmuz9z7HkEryiHAPY3ztjZB6RGLfnOXBMKEQfmduYDeGnD7F9QftpAHAgKaTCnsNbs/CidKoV39fVGjRzj+jxV1vbThMhuHCtKmQIDE5uZRRROM1DPAH4QfY4UXxdbqNovmILgkm/XnUe0XO+iA/M/F9OBlqPpQe8zWvgzXI8nQkNDv0pYhbiSVWGEqmwN9OHyGjv29deHA/TE6/5lCh8erO3Cj7YHHPmEZbgzNd0FV2TEc4dmoaE3gLzN/wPv6oQb0wp+4Fy02ajby3XEDz0uJ2X0s/TJNi5KS4Lg9ej3JUWnCKney2ME8KZI9OvCQQtwPA/7fvGGjpWbMG3QIDAQAB";

        public IHttpActionResult AliPay(dynamic Order)
        {
            IAopClient client = new DefaultAopClient(URL, APPID, APP_PRIVATE_KEY, FORMAT, "2.0", "RSA2", ALIPAY_PUBLIC_KEY, CHARSET, false);
            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称如：
            AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();//创建API对应的request类,请求返回二维码
            AlipayTradePagePayRequest requestPagePay = new AlipayTradePagePayRequest();//请求返回支付宝支付网页
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.Body = Order.Order.GoodsMs;
            model.Subject = Order.Order.OrderName;
            model.TotalAmount = Order.Order.Count;
            model.OutTradeNo = Order.Order.OrderNo;
            model.StoreId = "William001";
            model.ProductCode = "FAST_INSTANT_TRADE_PAY";
            requestPagePay.SetBizModel(model);
            requestPagePay.SetReturnUrl("http://39.101.132.124:8080/Movie/#/Order");
            var response = client.SdkExecute(requestPagePay);//Execute(request);
            if (!response.IsError)
            {
                var res = new
                {
                    success = true,
                    out_trade_no = response.OutTradeNo,
                    //qr_code = response.QrCode,    //二维码字符串
                    pay_url = URL + "?" + response.Body
                };
                return Ok(res);
            }
            else
            {
                var res = new
                {
                    success = false,
                };
                return Ok(res);
            }
        }
        public IHttpActionResult AddOrder(dynamic data)
        {
            using (filmEntities db = new filmEntities())
            {
                Orderinfo Order = new Orderinfo();
                Order.ScheduleID = data.data.ScheduleID;
                Order.Seat = data.data.Seat;
                Order.UserID = data.data.UserID;
                Order.VIPPrice = data.data.VIPPrice;
                Order.TotalPrice = data.data.TotalPrice;
                Order.OrderTime = data.data.OrderTime;
                db.Orderinfo.Add(Order);
                db.SaveChanges();
                return Ok();
            }
        }
        [System.Web.Http.HttpGet]
        public IHttpActionResult SelectOrderByID(int ID)
        {
            var OrderInfo1 = db.Orderinfo.Where(m => m.OrderID == ID).ToList().FirstOrDefault();

            return Ok(OrderInfo1);
        }

        [System.Web.Http.HttpGet]
        public IHttpActionResult GetOrederByUserID(int ID)
        {
            using (filmEntities db = new filmEntities())
            {
                //var OrderIn = db.Orderinfo.Where(o => o.UserID == ID);
                var Orderinfos = db.Orderinfo.Where(o => o.UserID == ID).ToList();
                var SID = Orderinfos.Select(s => s.ScheduleID);
                //查询排片信息
                List<Schedule> Sch = new List<Schedule>();
                foreach (var item in SID)
                {
                    Sch.Add(db.Schedule.Where(s => s.ScheduleID == item).FirstOrDefault());

                }
                //查询电影信息
                var MID = Sch.Select(m => m.MovieID);
                List<MovieInfo> Moin = new List<MovieInfo>();
                foreach (var item in MID)
                {
                    Moin.Add(db.MovieInfo.Where(m => m.MovieID == item).FirstOrDefault());
                }
                //查询影厅信息
                var HID = Sch.Select(h => h.HallID);
                List<Hall> halls = new List<Hall>();
                foreach (var item in HID)
                {
                    halls.Add(db.Hall.Where(c => c.HallID == item).FirstOrDefault());
                }

                var objDim = new List<Tuple<string, decimal, DateTime, string, string, string, int>>();
                for (int i = 0; i < Orderinfos.Count(); i++)
                {
                    objDim.Add(new Tuple<string, decimal, DateTime, string, string, string, int>(Orderinfos[i].Seat, Orderinfos[i].TotalPrice, Sch[i].StartTime, Moin[i].MovieImg, Moin[i].MovieName, halls[i].HallName, Orderinfos[i].OrderID));
                }
                
                return Ok(objDim);
            }

        }
        [System.Web.Http.HttpGet]
        public IHttpActionResult GetOrder() {
            using (filmEntities db = new filmEntities()) 
            {
                var Orderinfos = db.Orderinfo.ToList();
                var SID = Orderinfos.Select(s => s.ScheduleID);
                //查询排片信息
                List<Schedule> Sch = new List<Schedule>();
                foreach (var item in SID)
                {
                    Sch.Add(db.Schedule.Where(s => s.ScheduleID == item).FirstOrDefault());

                }
                //查询电影信息
                var MID = Sch.Select(m => m.MovieID);
                List<MovieInfo> Moin = new List<MovieInfo>();
                foreach (var item in MID)
                {
                    Moin.Add(db.MovieInfo.Where(m => m.MovieID == item).FirstOrDefault());
                }
                //查询影厅信息
                var HID = Sch.Select(h => h.HallID);
                List<Hall> halls = new List<Hall>();
                foreach (var item in HID)
                {
                    halls.Add(db.Hall.Where(c => c.HallID == item).FirstOrDefault());
                }

                var objDim = new List<Tuple<string, decimal, DateTime, int, string, string, int>>();
                for (int i = 0; i < Orderinfos.Count(); i++)
                {
                    objDim.Add(new Tuple<string, decimal, DateTime, int, string, string, int>(Orderinfos[i].Seat, Orderinfos[i].TotalPrice, Sch[i].StartTime, Orderinfos[i].UserID, Moin[i].MovieName, halls[i].HallName, Orderinfos[i].OrderID));
                }
                
                return Ok(objDim);
            }
        }

        [System.Web.Http.HttpGet]
        public IHttpActionResult DeleteByID(int ID)
        {
            using (filmEntities db = new filmEntities())
            {
                Orderinfo order = db.Orderinfo.Where(o => o.OrderID == ID).FirstOrDefault();
                DateTime ScheTime = db.Schedule.Where(S => S.ScheduleID == order.ScheduleID).Select(S => S.StartTime).FirstOrDefault();
                double hour = ( ScheTime- DateTime.Now).TotalHours;
                if (hour > 1)
                {
                    Refund refund = new Refund();
                    refund.OrderID = order.OrderID;
                    refund.RefundTime = DateTime.Now;
                    refund.ScheduleID = order.ScheduleID;
                    refund.Seat = order.Seat;
                    refund.TotalPrice = order.TotalPrice;
                    refund.UserID = order.UserID;
                    refund.VIPPrice = order.VIPPrice;



                    string[] Row = order.Seat.Split('=');
                    string[] IntCol = Row[0].Split(',');
                    int a = 0;
                    int b = 0;
                    var hall = db.Schedule.Where(H => H.ScheduleID == order.ScheduleID).Select(H => H.SeatSell).FirstOrDefault();
                    string[] HallRow = hall.Split('=');
                    string[] StringHallCol = HallRow[0].Split(','); //string[,]是等长数组，列维度一样，只要取任意一行的列维度即可确定整个二维数组的列维度
                    int[] IntHallCol = Array.ConvertAll<string, int>(StringHallCol, delegate (string s) { return int.Parse(s); });
                    int x = HallRow.Length;
                    int y = StringHallCol.Length;
                    int[,] twoArray = new int[x, y];
                    for (int i = 0; i < x; i++)
                    {
                        StringHallCol = HallRow[i].Split(',');
                        IntHallCol = Array.ConvertAll<string, int>(StringHallCol, delegate (string s) { return int.Parse(s); });
                        for (int j = 0; j < IntHallCol.Length; j++)
                        {
                            twoArray[i, j] = IntHallCol[j];
                        }
                    }
                    for (int i = 0; i < Row.Length; i++)
                    {
                        IntCol = Row[i].Split(',');
                        IntHallCol = Array.ConvertAll<string, int>(IntCol, delegate (string s) { return int.Parse(s); });
                        a = IntHallCol[0]-1;
                        b = IntHallCol[1]-1;
                        twoArray[a,b] = 0;
                        
                    }
                    

                    var Seat = "";
                    for (int i = 0; i < x; i++)
                    {
                        for (int j = 0; j < y; j++)
                        {
                            Seat += twoArray[i, j];
                            if (j != y - 1)
                            {
                                Seat += ",";
                            }
                        }
                        if (i != x - 1)
                        {
                            Seat += "=";
                        }
                    }
                    var hall2 = db.Schedule.Where(H => H.ScheduleID == order.ScheduleID).FirstOrDefault();
                    hall2.SeatSell = Seat;
                    db.Refund.Add(refund);
                    db.Orderinfo.Remove(order);
                    db.Entry(hall2).State = EntityState.Modified;
                    if (db.SaveChanges() >= 3)
                    {
                        //返回1表示修改成功
                        return Ok(1);
                    }
                    else
                    {
                        //返回2表示修改失败
                        return Ok(2);
                    }

                }
                else {
                    //返回3表示时间大于一小时，不能退票
                    return Ok(3);
                }

            }

        }

        [System.Web.Http.HttpGet]
        public IHttpActionResult GetMoNameAndMoney() 
        {
            using (filmEntities db = new filmEntities())
            {
                var Money = db.Orderinfo.GroupBy(O => new { ID = O.Schedule.MovieID }).Select(O => new { ID = O.Key.ID, Total = O.Sum(T => T.TotalPrice) }).ToList();
                //var SID = Money.Select(a => a.ID);
                //List<Schedule> schedules = new List<Schedule>();
                //foreach (var item in SID)
                //{
                //    schedules.Add(db.Schedule.Where(s => s.ScheduleID == item).FirstOrDefault());
                //}
                //var MID = schedules.Select(b=>b.MovieID);
                List<MovieInfo> movieInfos = new List<MovieInfo>();
                foreach (var item in Money)
                {
                    movieInfos.Add(db.MovieInfo.Where(c=>c.MovieID==item.ID).FirstOrDefault());
                }
                var objDim = new List<Tuple<string, decimal>>();
                for (int i = 0; i < Money.Count(); i++)
                {
                    objDim.Add(new Tuple<string, decimal>(movieInfos[i].MovieName, Money[i].Total));
                }
                return Ok(objDim);
            }
        }
        public IHttpActionResult GetDateandMoney()
        {
            using (filmEntities db=new filmEntities())
            {
                var Dates = db.Orderinfo.GroupBy(O => O.Schedule.StartTime.Month+"月"+ O.Schedule.StartTime.Day+"日").Select(O => new { date = O.Key, Total = O.Sum(T => T.TotalPrice) }).ToList();
                
                var objDim = new List<Tuple<string, decimal>>();
                for (int i = 0; i < Dates.Count(); i++)
                {
                    objDim.Add(new Tuple<string, decimal>(Dates[i].date, Dates[i].Total));
                }
                return Ok(objDim);
            }
        }
        [System.Web.Http.HttpGet]
        public IHttpActionResult GetReFundByUserID(int ID)
        {
            using (filmEntities db = new filmEntities())
            {
                //var OrderIn = db.Orderinfo.Where(o => o.UserID == ID);
                var Orderinfos = db.Refund.Where(o => o.UserID == ID).ToList();
                var SID = Orderinfos.Select(s => s.ScheduleID);
                //查询排片信息
                List<Schedule> Sch = new List<Schedule>();
                foreach (var item in SID)
                {
                    Sch.Add(db.Schedule.Where(s => s.ScheduleID == item).FirstOrDefault());

                }
                //查询电影信息
                var MID = Sch.Select(m => m.MovieID);
                List<MovieInfo> Moin = new List<MovieInfo>();
                foreach (var item in MID)
                {
                    Moin.Add(db.MovieInfo.Where(m => m.MovieID == item).FirstOrDefault());
                }
                //查询影厅信息
                var HID = Sch.Select(h => h.HallID);
                List<Hall> halls = new List<Hall>();
                foreach (var item in HID)
                {
                    halls.Add(db.Hall.Where(c => c.HallID == item).FirstOrDefault());
                }

                var objDim = new List<Tuple<string, decimal, string, string, string, string, int>>();
                for (int i = 0; i < Orderinfos.Count(); i++)
                {
                    objDim.Add(new Tuple<string, decimal, string, string, string, string, int>(Orderinfos[i].Seat, Orderinfos[i].TotalPrice, Orderinfos[i].RefundTime.ToString("yyyy-MM-dd HH:mm:ss"), Moin[i].MovieImg, Moin[i].MovieName, halls[i].HallName, Orderinfos[i].OrderID));
                }

                return Ok(objDim);
            }

        }
    }
}
